import styles from './index.less'
import { DEFAULT_LOGO, DEFAULT_NAME, PLATFORM_URL } from '@/constants'
import { useModel, useSearchParams, history } from '@umijs/max'
import md5 from 'js-md5'

import { LockOutlined, MobileOutlined, UserOutlined, LeftOutlined } from '@ant-design/icons'
import { LoginForm, ProFormCaptcha, ProFormCheckbox, ProFormText } from '@ant-design/pro-components'
import { Tabs, App } from 'antd'
import { useState } from 'react'
import { setCookie, getDomain, crypt, setAccessToken, checkTarget } from '@/utils/utils'

type LoginType = 'phone' | 'account'

const Login = () => {
  const { message } = App.useApp()
  const { Login, GetCapture, SendResetPwdSms, ResetPwd } = useModel('Global')
  const [searchParams] = useSearchParams()
  const [loginType, setLoginType] = useState<LoginType>('account')
  const [isForgotPassword, setIsForgotPassword] = useState<Boolean>(false)

  const handleSubmit = async (values: any) => {
    if (isForgotPassword) {
      console.log('values', values)
      const res = await ResetPwd(values)
      console.log('res', res)
      if (res) {
        message.success('密码重置成功')
        setIsForgotPassword(false)
      }
    } else {
      const { autoLogin } = values

      if (values.pwd) values.pwd = md5(values.pwd)

      Login(values).then((res: any) => {
        if (res && res.length) {
          const target = checkTarget(searchParams.get('target'))
          message.success('登录成功')
          if (res.length === 1) {
            const { platform_type } = res[0]
            const token = res[0]['jwt-token']

            setAccessToken(platform_type - 1, token, autoLogin)
            setCookie('autoL', autoLogin, getDomain(), autoLogin)

            setTimeout(() => {
              history.push((PLATFORM_URL as any)[platform_type - 1] + (target || '/'))
            }, 200)
          } else {
            const a = JSON.stringify(res)
            const coa = crypt.encode(a)
            setCookie('roleList', coa, getDomain(), autoLogin)
            setCookie('autoL', autoLogin, getDomain(), autoLogin)
            history.push(`/main/rolePicker?target=${target}`)
          }
        }
      })
    }
  }

  const tabItems = [
    { label: '账号密码登录', key: 'account' },
    { label: '手机号登录', key: 'phone' }
  ]

  return (
    <div className={styles.login_content}>
      <LoginForm
        title={
          isForgotPassword ? (
            <div className={styles.login_title}>
              <LeftOutlined className={styles.back_icon} onClick={() => setIsForgotPassword(false)} />
              <div>密码重置</div>
            </div>
          ) : (
            `欢迎来到${DEFAULT_NAME}`
          )
        }
        subTitle={' '}
        submitter={{ searchConfig: { submitText: isForgotPassword ? '重置密码' : '登录' } }}
        initialValues={{
          autoLogin: true
        }}
        onFinish={async values => {
          handleSubmit(values)
        }}
        className={styles.login_form_block}
      >
        {!isForgotPassword ? (
          <Tabs
            // centered
            activeKey={loginType}
            onChange={activeKey => setLoginType(activeKey as LoginType)}
            items={tabItems}
          />
        ) : null}
        {isForgotPassword ? (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={'prefixIcon'} />
              }}
              name='account'
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！'
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！'
                }
              ]}
            />

            <ProFormText.Password
              name='password'
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />
              }}
              placeholder={'新密码'}
              rules={[
                {
                  required: true,
                  message: '新密码'
                }
              ]}
            />

            <ProFormText.Password
              name='password_confirmation'
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />
              }}
              placeholder={'再次输入新密码'}
              rules={[
                {
                  required: true,
                  message: '再次输入新密码'
                },
                ({ getFieldValue }) => ({
                  validator(_: any, value: any) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('两次密码不一致'))
                  }
                })
              ]}
            />

            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />
              }}
              captchaProps={{
                size: 'large'
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`
                }
                return '获取验证码'
              }}
              name='code'
              phoneName='account'
              rules={[
                {
                  required: true,
                  message: '请输入验证码！'
                }
              ]}
              onGetCaptcha={async (account: string) => {
                // 获取验证码
                let params = {
                  account
                }
                let res = await SendResetPwdSms(params)
                if (res) {
                  message.success('获取验证码成功,请注意查收')
                }
              }}
            />
          </>
        ) : loginType === 'account' ? (
          <>
            <ProFormText
              name='account'
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />
              }}
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!'
                }
              ]}
            />
            <ProFormText.Password
              name='pwd'
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />
              }}
              placeholder={'请输入密码！'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！'
                }
              ]}
            />
          </>
        ) : loginType === 'phone' ? (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={'prefixIcon'} />
              }}
              name='account'
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！'
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！'
                }
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />
              }}
              captchaProps={{
                size: 'large'
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`
                }
                return '获取验证码'
              }}
              name='code'
              phoneName='account'
              rules={[
                {
                  required: true,
                  message: '请输入验证码！'
                }
              ]}
              onGetCaptcha={async (account: string) => {
                // 获取验证码
                let params = {
                  phone: account
                }
                let res = await GetCapture(params)
                if (res) {
                  message.success('获取验证码成功,请注意查收')
                }
              }}
            />
          </>
        ) : null}

        <div
          style={{
            marginBlockEnd: 24,
            minHeight: 22
          }}
        >
          {isForgotPassword ? null : (
            <ProFormCheckbox noStyle name='autoLogin'>
              自动登录
            </ProFormCheckbox>
          )}
          {/* {isForgotPassword ? (
            <a
              style={{
                float: 'right'
              }}
              onClick={() => setIsForgotPassword(false)}
            >
              返回登录
            </a>
          ) : loginType === 'account' ? (
            <a
              style={{
                float: 'right'
              }}
              onClick={() => setIsForgotPassword(true)}
            >
              忘记密码
            </a>
          ) : null} */}
          {isForgotPassword ? null : loginType === 'account' ? (
            <a
              style={{
                float: 'right'
              }}
              onClick={() => setIsForgotPassword(true)}
            >
              忘记密码
            </a>
          ) : null}
        </div>
      </LoginForm>
    </div>
  )
}

export default Login
